import json

from django.shortcuts import render
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from django.views.generic.base import View
from django.contrib.auth.hashers import make_password
from django.http import HttpResponse,HttpResponseRedirect

from pure_pagination import Paginator,EmptyPage,PageNotAnInteger



from .models import UserProfile,EmailVerifyRecord,Banner
from .forms import LoginForm,RegisterForm,ForgetForm,ModifyPwdForm,ImageUploadForm,UserInfoForm
from operation.models import UserCourse,UserFavorite,UserMessage
from organization.models import CourseOrg,Teacher
from courses.models import Course

from utils.email_send import send_register_email
from utils.mixin_utils import LoginRequiredMixin



# Create your views here.

class CustomBackend(ModelBackend):
    #print('start custom')
    """
       自定义用户验证规则
    """
    def authenticate(self,request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            print("用户登录验证异常except:", e)
            return None
    #print('end custom')


class ActiveUserView(View):
    def get(self,request,active_code):
        all_records=EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email=record.email
                user=UserProfile.objects.get(email=email)
                user.is_active=True
                user.save()
        else:
            return  render(request,'active_fail.html')
        return render(request,"login.html")


class RegisterView(View):
    def get(self, request):
        register_form=RegisterForm()
        return render(request, 'register.html', {'register_form':register_form})

    def post(self,request):
        register_form=RegisterForm(request.POST)
        if register_form.is_valid():
            user_name = request.POST.get('email','')
            if UserProfile.objects.filter(email=user_name):
                return render(request,'register.html',{"msg":"用户已经存在",'register_form':register_form})
            pass_word = request.POST.get('password','')
            user_profile=UserProfile()
            user_profile.nick_name = user_name
            user_profile.email=user_name
            user_profile.password = make_password(pass_word)
            user_profile.is_active=False
            user_profile.save()


            #增加消息
            user_message=UserMessage()
            user_message.user=user_profile.id
            user_message.comments="欢迎来到测试学院来进行学习，谢谢你的注册"
            user_message.save()

            send_register_email(user_name,'register')
            return render(request,'login.html')
        else:
            return render(request,'register.html',{"register_form":register_form})


#含有sql注入漏洞的类方法实现登陆，后续不要用，实验用
class LoginUnsafeView(View):
    def get(self,request):
        return render(request, 'login.html', {})
    def post(self,request):
        user_name = request.POST.get('username', '')
        pass_word = request.POST.get('password', '')

        import  MySQLdb
        conn=MySQLdb.connect(host="127.0.0.1",user="root",passwd="310012",port=3307,db="mxonline",charset="utf8")
        cursor=conn.cursor()
        sql_select="select * from users_userprofile where email='{0}' and password='{1}'".format(user_name,pass_word)
        reslut=cursor.execute(sql_select)
        for row in cursor.fetchall():
            #有结果
            print("sql注入后，成功登陆")
            return render(request, 'index.html')

        #否则失败
        print("失败")
        return render(request, 'login.html')



#类方法实现登陆，后续使用
class LoginView(View):
    def get(self,request):
        return render(request, 'login.html', {})
    def post(self,request):
        login_form=LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username', '')
            pass_word = request.POST.get('password', '')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, 'index.html')
                else:
                    return render(request,'login.html',{"msg":"用户未激活！请先到注册邮箱激活"})
            else:
                return render(request, 'login.html', {"msg": "用户名或密码错误！"})
        else:
            return render(request, 'login.html', {"login_form":login_form})

class LogoutView(View):
    def get(self,request):
        logout(request)
        from django.urls import reverse
        return HttpResponseRedirect(reverse("index"))

#函数方法实现登陆，后续不用了
def user_login(request):
    if request.method=='POST':
        user_name=request.POST.get('username','')
        pass_word=request.POST.get('password','')
        #不知道密码后，重设密码
        # user = UserProfile.objects.get(username='root')
        # user.set_password('310012')
        # user.save()
        # quit()
        user=authenticate(username=user_name,password=pass_word)
        if user is not None:
            login(request,user)
            return render(request,'index.html')
        else:
            return render(request, 'login.html', {"msg":"用户名或密码错误！"})

    elif request.method=='GET':
        return render(request,'login.html',{})


class ForgetPwdView(View):
    def get(self,request):
        forget_form=ForgetForm()
        return render(request,"forgetpwd.html",{"forget_form":forget_form})

    def post(self, request):
        forget_form = ForgetForm(request.POST)
        # 忘记密码表单是否合法
        if forget_form.is_valid():
            email = request.POST.get('email', "")
            send_register_email(email, "forget")
            return render(request, "send_success.html")
        else:
            return render(request, "forgetpwd.html", {'forget_form': forget_form})

class ResetView(View):
    def get(self,request,active_code):
        all_records=EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for record in all_records:
                email=record.email
                return render(request,'password_reset.html',{"email":email})
        else:
            return  render(request,'active_fail.html')
        return render(request,"login.html")


class ModifyPwdView(View):
    def post(self,request):
        modify_form=ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1=request.POST.get("password1","")
            pwd2=request.POST.get("password2","")
            email=request.POST.get("email","")
            if pwd1!=pwd2:
                return render(request,"password_reset.html",{"email":email,"msg":"2次密码不一致"})
            user=UserProfile.objects.get(email=email)
            user.password=make_password(pwd1)
            user.save()
            return  render(request,"login.html")
        else:
            email=request.POST.get("email","")
            return  render(request,"password_reset.html",{"email":email})


class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        return render(request,'usercenter-info.html',{
        })

    def post(self,request):
        userInfo_Form=UserInfoForm(request.POST,instance=request.user)
        if userInfo_Form.is_valid():
            userInfo_Form.save()
            return HttpResponse('{"status":"success"}',content_type="application/json")
        else:
            return HttpResponse(json.dumps(userInfo_Form.errors),content_type="application/json")



class ImageUploadView(LoginRequiredMixin,View):
    """
    用户上传头像
    """
    def post(self,request):
        image_form=ImageUploadForm(request.POST,request.FILES,instance=request.user)
        if image_form.is_valid():
            image_form.save()
            return HttpResponse("{'status':'success'}",content_type="application/json")
        else:
            return HttpResponse("{'status':'fail'}",content_type="application/json")

class UpdatePwdView(LoginRequiredMixin,View):
    """
    用户个人中心的改密
    """
    def post(self,request):
        modify_form=ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1=request.POST.get("password1","")
            pwd2=request.POST.get("password2","")
            if pwd1!=pwd2:
                return HttpResponse('{"status":"fail","msg":"2次密码不一致"}', content_type="application/json")
            user=request.user
            user.password=make_password(pwd1)
            user.save()
            return HttpResponse('{"status":"success"}',content_type="application/json")
        else:
            return HttpResponse(json.dumps(modify_form.errors),content_type="application/json")


class SendEmailCodeView(LoginRequiredMixin,View):
    """
    个人中心修改密码用的发送邮箱
    """
    def get(self,request):
        email=request.GET.get('email','')
        if UserProfile.objects.filter(email=email):
            return HttpResponse('{"email":"邮箱已经存在，请换一个再试"}',content_type="application/json")
        else:
            send_register_email(email,"update_email")
            return HttpResponse('{"status":"success"}',content_type="application/json")


class UpdateEmailView(LoginRequiredMixin,View):
    """
    修改密码
    """
    def post(self,request):
        email=request.POST.get('email',"")
        code=request.POST.get('code',"")
        existed_records=EmailVerifyRecord.objects.filter(email=email,send_type='update_email')
        if existed_records:
            user=request.user
            user.email=email
            user.save()
            return HttpResponse('{"status":"success"}',content_type="application/json")
        else:
            return HttpResponse('{"email":"验证码不正确，请确认后再试"}',content_type="application/json")


class MyCourses(LoginRequiredMixin,View):
    """
    我的课程
    """
    def get(self,request):
        user_courses=UserCourse.objects.filter(user=request.user)
        return render(request,"usercenter-mycourse.html",{
            "user_courses":user_courses
        })


class MyFavOrgView(LoginRequiredMixin,View):
    """
    我的收藏的机构
    """
    def get(self,request):
        org_list=[]
        user_fav_orgs=UserFavorite.objects.filter(user=request.user,fav_type=2)
        for fav_org in user_fav_orgs:
            org_id=fav_org.fav_id
            org=CourseOrg.objects.get(id=org_id)
            org_list.append(org)
        return render(request,"usercenter-fav-org.html",{
            "org_list":org_list
        })


class MyFavTeacherView(LoginRequiredMixin,View):
    """
    我的收藏的讲师
    """
    def get(self,request):
        teacher_list=[]
        user_fav_teachers=UserFavorite.objects.filter(user=request.user,fav_type=3)
        for fav_teacher in user_fav_teachers:
            teacher_id=fav_teacher.fav_id
            teacher=Teacher.objects.get(id=teacher_id)
            teacher_list.append(teacher)
        return render(request,"usercenter-fav-teacher.html",{
            "teacher_list":teacher_list
        })

class MyFavCourseView(LoginRequiredMixin,View):
    """
    我的收藏的讲师
    """
    def get(self,request):
        course_list=[]
        user_fav_courses=UserFavorite.objects.filter(user=request.user,fav_type=1)
        for fav_course in user_fav_courses:
            course_id=fav_course.fav_id
            course=Course.objects.get(id=course_id)
            course_list.append(course)
        return render(request,"usercenter-fav-course.html",{
            "course_list":course_list
        })


class MyMessageView(LoginRequiredMixin,View):
    """
    用户消息
    """
    def get(self,request):
        all_messages=UserMessage.objects.filter(user=request.user.id)
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_messages, 5, request=request)
        messages=p.page(page)
        return  render(request,"usercenter-message.html",{
            "messages":messages
        })


class IndexView(View):
    def get(self,request):
        all_banners=Banner.objects.all().order_by('index')
        courses=Course.objects.filter(is_banner=False)[:6]
        banner_courses=Course.objects.filter(is_banner=True)[:3]
        course_orgs=CourseOrg.objects.all()[:15]
        return render(request,'index.html',{
            "all_banners":all_banners,
            "courses":courses,
            "banner_courses":banner_courses,
            "course_orgs":course_orgs
        })






















